package user

import (
	"errors"
	"fmt"
	"hft/Database/admin/user_db"
	"hft/Http/Models/dao"
	"hft/Http/Services/base"
	"hft/Http/Services/user/user_dao"
	"hft/Http/Services/user/user_model"
	"hft/Http/Services/user/user_utils"
	utils "hft/Http/Utils"
	"hft/e"
	"hft/global"
	"hft/tools"
	"regexp"
)

type User struct{}

func (*User) List(paginate *user_model.UserSearchParams, claims tools.BaseClaims) (data *utils.Page, err error) {
	account, err := base.FindAccount(claims, global.OC_DB)
	if err != nil {
		return nil, err
	}
	var list []*user_model.FindUserList
	global.OC_DB.Model(&user_db.User{}).Where("city_link LIKE ?", fmt.Sprintf("%v%%", account.RegionLink)).Scopes(user_dao.UserDao.List(account.RegionLink, paginate, global.OC_DB)).Find(&list).Scopes(dao.GetCount(global.OC_DB)).Count(&paginate.Total)
	var newList = make([]*user_model.UserList, 0)
	var ids []int
	for _, v := range list {
		ids = append(ids, v.ID)
	}
	var intendRegionList []*user_model.IntendRegionList
	global.OC_DB.Table("hft_front_user_region").Where("user_id IN ?", ids).Find(&intendRegionList)
	for _, v := range list {
		var item = &user_model.UserList{
			ID:             int(v.ID),
			Phone:          v.Phone,
			Name:           v.Username,
			OriginName:     user_utils.GetOriginName(v.FC_port, v.FC_activity_name),
			City:           v.CityName,
			IntendLou:      v.IntendLou,
			Level:          v.Level,
			FirstInTime:    v.FirstClueTime.Format("2006-01-02 15:04:05"),
			CreateTime:     v.CreateTime.Format("2006-01-02 15:04:05"),
			LastUpdateTime: v.UpdateTime.Format("2006-01-02 15:04:05"),
			Ip:             v.Ip,
			Valid:          v.IsValid,
			Port:           v.FC_port,
			IsShield:       v.IsShield,
		}
		for _, j := range intendRegionList {
			if v.ID == j.UserID {
				if j.RegionName != "" {
					item.RegionList = append(item.RegionList, j.RegionName)
				}

			}
		}
		newList = append(newList, item)
	}
	paginate.Data = newList
	return &paginate.Page, nil
}

func (*User) Detail(claims tools.BaseClaims, id int) (data interface{}, err error) {
	if account, err := base.FindAccount(claims, global.OC_DB); err != nil {
		return nil, err
	} else {
		var detail *user_db.User
		err := global.OC_DB.First(&detail, id).Error
		if err != nil {
			return nil, errors.New(e.UserNotFound)
		}
		if ok, _ := regexp.MatchString(fmt.Sprintf("^%v", account.RegionLink), detail.CityLink); !ok {
			return nil, errors.New(e.NoRightToOpera)
		} else {
			// 找出线索
			var clueList []*user_model.ClueItem
			global.OC_DB.Model(&user_db.Clue{}).Order("create_time desc").Preload("PhoneRecord").Preload("HelpSelect").Preload("Reservation").Where("user_id = ?", detail.ID).Find(&clueList)
			for _, v := range clueList {
				v.OriginName = user_utils.GetOriginName(v.Port, v.ActivityName)
			}
			followList := user_utils.FindFollowUp(detail)
			var newData = &user_model.UserDetail{
				CreateTime:       detail.CreateTime.Format("2006-01-02 15:04:05"),
				UseTimes:         detail.UseProtectTimes,                           //使用次数
				ProtectTimes:     detail.ReleaseTime.Format("2006-01-02 15:04:05"), //释放时间
				FollowTimes:      detail.HistoryManagerNum,
				Username:         detail.Username,
				Level:            detail.Level,
				NowBroker:        detail.ManagerName,
				FirstInTime:      detail.FirstClueTime.Format("2006-01-02 15:04:05"), //管家首次跟进时间
				Phone:            detail.Phone,
				Valid:            user_utils.IsValid(detail.IsValid),
				NewestFollowTime: detail.UpdateTime.Format("2006-01-02 15:04:05"),
				ClueList:         clueList,
				City:             detail.CityName,
				FollowList:       followList,
			}
			return newData, nil
		}
	}
}

// 屏蔽电话
func (*User) ShieldPhone(id int, claims tools.BaseClaims, shield bool) (err error) {
	account, err := base.FindAccount(claims, global.OC_DB)
	var user *user_db.User
	if err = global.OC_DB.Where("id = ?", id).First(&user).Error; err != nil {
		return errors.New(e.UserNotFound)
	}
	if match, _ := regexp.MatchString(fmt.Sprintf("^%v", account.RegionLink), user.CityLink); !match {
		return errors.New(e.NoRightToOpera)
	}
	if res := global.OC_DB.Model(&user).Where("id = ?", user.ID).Update("is_shield", shield); res.RowsAffected == 0 || res.Error != nil {
		return errors.New(e.ErrorInfo)
	}
	return nil
}

var UserService = new(User)
